#include "common-header.h"

#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif

int main(int argc, char* argv[]) {
  if ((argc == 2 && equals(argv[1], "--help")) || argc != 3) {
    usage("%s old-file new-file\n", argv[0]);
  }

  int input_fd = open(argv[1], O_RDONLY);
  if (input_fd == -1) {
    error("opening file %s", argv[1]);
  }

  int output_fd = open(argv[2],
                       O_CREAT | O_WRONLY | O_TRUNC,
                       S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
  if (output_fd == -1) {
    error("opening file %s", argv[2]);
  }

  char buf[BUF_SIZE];
  ssize_t num_read;
  while ((num_read = read(input_fd, buf, BUF_SIZE)) > 0) {
    if (write(output_fd, buf, num_read) != num_read) {
      fatal("couldn't write whole buffer");
    }
  }
  if (num_read == -1) {
    error("read");
  }

  if (close(output_fd) == -1) {
    error("close output");
  }
  if (close(input_fd) == -1) {
    error("close input");
  }

  return EXIT_SUCCESS;
}
